package com.jiajia.server.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiajia.server.controller.MailLogController;
import com.jiajia.server.mapper.MailLogMapper;
import com.jiajia.server.pojo.MailConstants;
import com.jiajia.server.pojo.MailLog;
import com.jiajia.server.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ZSJia
 * @date 2021/8/20 020 - 14:19
 */
@Configuration
public class RabbitmqConfig {
    private final static Logger LOGGER = LoggerFactory.getLogger(RabbitmqConfig.class);

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    private IMailLogService mailLogService;

    //rabbitmqtimeplate
    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调,确认消息是否到达broker
         * correlationData 为消息唯一标识（msgId）
         * ack               回调结果（成功为true）
         * cause           失败原因
         */
        rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
            String msgId = correlationData.getId();
            System.out.println("msgId:"+msgId);
            if (ack){
                LOGGER.info("消息发送成功======>{}",msgId);
                //数据库消息改为成功
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",1).eq("msgId",msgId));
            }else {
                LOGGER.error("消息发送失败======>{}",msgId);
            }
        });

        /**
         * 消息失败回调，比如router不到queue时回调
         * msg 消息主题
         * repCode 响应码
         * repText 响应描述
         * exchange 交换机
         * routingkey 路由键
         */
        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routingkey)->{
                LOGGER.error("{}======>消息发送queue时失败", msg.getBody());
            });

        return rabbitTemplate;
    }


    //开启通道
    @Bean
    public Queue queue(){
        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    //开启交换机
    @Bean
    public DirectExchange exchange(){
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }


    //通道与交换机绑定
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(exchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }
}
